/*
 *    This file is part of CeluMap.
 *
 *    CeluMap is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU Lesser General Public License as published by
 *    the Free Software Foundation; either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    CeluMap is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    Copyright 2006, 2007, 2008 Gonzalo Merayo
 *    gonzalo (at) celumap.com.ar
 *    www.celumap.com.ar
 *
 */

package figures.basic;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;

import map.file.FileMap;

public class NameManager {
	private byte[] p = new byte[0];
	byte[] buffer = new byte[0];
	public NameManager(){
		
	}
	public NameManager(byte[] name, byte[] offsets){
		p = name;
		buffer = offsets;
	}
	public int addName(byte[] n){
		int slength = 0;
		for(;slength<n.length && n[slength]!=0;slength++);
		byte[] tmp = new byte[p.length+slength];
		System.arraycopy(p, 0, tmp, 0, p.length);
		System.arraycopy(n, 0, tmp, p.length, slength);
		int l = p.length;
		p = tmp;
		int r = (l<<8)|(slength&0xFF);
		return r;
	}
	/*
	static byte[] b = new byte[20];
	public byte[] getName(int i){
		if(b.length<=(i&0xFF))
			b = new byte[(i&0xFF)+1];
		System.arraycopy(p, (i>>8)&0xFFFFFF, b, 0, i&0xFF);
		b[i&0xFF] = 0;
		return b;
	    
	}
	*/
	public byte[] getName(int i){
		byte[] b = new byte[i&0xFF];
		System.arraycopy(p, (i>>8)&0xFFFFFF, b, 0, i&0xFF);
		return b;
	    
	}
	public void load(InputStream is) throws IOException {
		buffer = new byte[4];
		is.read(buffer, 0, 4);
		int l = FileMap.byteArrayToInt(buffer,0);
		p = new byte[l];
		is.read(p, 0, l);
		is.read(buffer, 0, 4);
		l = FileMap.byteArrayToInt(buffer,0);
		buffer = new byte[l];
		is.read(buffer, 0, l);
	}
	
	public void unload(DataOutputStream os) throws IOException {
		os.writeInt(p.length);
		os.write(p);
		os.writeInt(buffer.length);
		os.write(buffer);
	}
	
	public int addOffsets(byte[] n){
		byte[] tmp = new byte[buffer.length+n.length];
		System.arraycopy(buffer, 0, tmp, 0, buffer.length);
		System.arraycopy(n, 0, tmp, buffer.length, n.length);
		int l = buffer.length;
		buffer = tmp;
		return l;
	}
}
